package top.hencter.weibo.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.hencter.weibo.R;
import top.hencter.weibo.adapter.IndexListAdapter;
import top.hencter.weibo.bean.IndexItem;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link IndexFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class IndexFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ListView listView;
    private IndexListAdapter mainListAdapter;
    private int currentPage = 0; // 当前请求的页数

    public IndexFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static IndexFragment newInstance(String param1, String param2) {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        // 加载布局，生成对应的view
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        // 用 ListView 来渲染获取的到的数据
        listView = view.findViewById(R.id.index_list_view);
        // 调用请求方法，该请求方法每次被使用都会将页数 + 1
        // 报错: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        // 解决如下将 listView 作为参数传入方法中这样方法里面就能够调用这个 ListView 对象了
        getList(listView);
        // 给 listView 添加滚动监听事件
        // 这里要重点理解下 absListView.getLastVisiblePosition() >= absListView.getCount() - 2这个判断条件
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断是否到底部
                        if (view.getLastVisiblePosition() >= view.getCount() - 2) {
                            // 获取下一页数据
                            getList(listView);
                        }
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        return view;
    }

    public void getList(ListView listView) {
        currentPage++;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://129.28.159.96:7001/v1/test/getWeiboList?page=" + currentPage)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.i("======", e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String data = response.body().string();
                Gson gson = new Gson();
                Log.i("======", data);
                final ArrayList<IndexItem> mainItems;
                mainItems = gson.fromJson(data, new TypeToken<ArrayList<IndexItem>>() {
                }.getType());
                getActivity().runOnUiThread(() -> {
                    if (currentPage == 1) {
                        mainListAdapter = new IndexListAdapter(getActivity(), R.layout.index_list_item, mainItems);
                        listView.setAdapter(mainListAdapter);
                    } else {
                        mainListAdapter.addAll(mainItems);
                    }
                });
            }
        });
    }
}